import React, {Component} from "react";
import Header from "./components/Header";
import List from "./components/List";
import Footer from "./components/Footer"

export default class App extends Component {
    //三大核心之一状态管理
    state = {
        todos: [
            {id: 1, name: '打豆豆', state: true},
            {id: 2, name: '打憨憨', state: true},
            {id: 3, name: '打屁屁', state: true},
            {id: 4, name: '打妖怪', state: true},
            {id: 5, name: '打飞机', state: false},
        ]
    }
    //添加一个元素
    save = (name: string) => {
        this.state.todos.push(
            {
                'id': this.state.todos.length + 5,
                'name': name,
                'state': false
            }
        );
        //this.setState 是异步的会导致渲染值与实际变量不一直，当在渲染后需要立即得到最新值时，可以在回调函数中获取。
        this.setState({todos: this.state.todos}, () => {
            console.log(this.state.todos)
        })
    }
    //编辑 移除一个元素
    edit = (id: number, flag:boolean) => {
        const {todos} = this.state;
        for (let i = 0; i < todos.length; i++) {
            const todo = todos[i];
            if(todo.id!==id){
                continue
            }
            if(flag  ===undefined){
                const  newTodos= todos.filter((obj)=>{
                    return obj.id != todo.id;
                })
                this.setState({todos:newTodos})
                break
            }else {
                todos[i].state=flag;
                this.setState({todos:todos})
                break
            }
        }
    }

    render() {
        //从state中取出 todos这个属性
        const {todos} = this.state;
        return (
            <div>
                <h1>---------------------------案例一--------------------------------------</h1>
                <Header save={this.save}/>
                <List todos={todos} edit={this.edit}/>
                <Footer/>
                <h1>---------------------------案例一--------------------------------------</h1>
            </div>
        )
    }

}
